package com.gupao.edu.homework.chatroom;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * @description：服务端
 * @author：GP16803-林华滨
 * @version：2018年11月01日 13:28
 */
public class Server {

    /***
     * 服务端默认端口
     */
    private static int DEFAULT_PORT = 11111;

    /***
     * 单例的ServerSocket
     */
    private static ServerSocket serverSocket;

    /***
     * 聊天室的所有成员
     */
    private static List<ServerHandler> chatRoomMembers = new ArrayList<ServerHandler>(0);

    /***
     * 服务端默认端口启动
     * @throws IOException
     */
    public void start() throws IOException {
        start(DEFAULT_PORT);
    }

    /***
     * 服务端指定端口启动
     * @param port
     */
    public synchronized void start(int port) throws IOException {
        if (null != serverSocket) {
            return;
        }
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("服务端已启动，端口号：" + port);

            while (true) {
                Socket socket = serverSocket.accept();
                ServerHandler member = new ServerHandler(socket, chatRoomMembers);
                // 保存所有在聊天室的成员
                chatRoomMembers.add(member);
                new Thread(member).start();

                System.out.println("服务端现有的连接数：" + chatRoomMembers.size());
            }
        } finally {
            if (null != serverSocket) {
                System.out.println("服务端已关闭。");
                serverSocket.close();
                serverSocket = null;
            }
        }
    }
}
